package cn.tedu.mr;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;

/**
 * LongWritable:k1: 行的偏移量
 * Text:v1: 一行的值
 * Text:k2：统计的词
 * IntWritable:v2: 词出现一次
 *
 * @author Amos
 * @date 2022/5/10
 */

// hello world hello
public class WordMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
    /**
     * 每来一条数据，调用一次map方法
     *
     * @param key     k1
     * @param value   v1
     * @param context 上下文，将数据写出
     * @throws IOException
     * @throws InterruptedException
     */
    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        // 获取一行数据hello world -> hello 1
        String line = value.toString();
        // 按照" "拆分词
        String[] words = line.split(" ");

        // 将每一个词，按照(词，1)格式输出
        for (String word : words) {
            context.write(new Text(word), new IntWritable(1));
        }
    }
}
